import { UserRepository } from "@/examples/user/user.repository";
import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import argon2 from "argon2";

@Injectable()
export class AuthService {

    constructor(private readonly userRepository: UserRepository, private jwt: JwtService) {}

	async signin (username: string, password: string) {
        const user = await this.userRepository.findOne(username);
        if(!user) {
            throw new Error("用户名不存在");
        }

        const isPasswordValid = await argon2.verify(user.password, password)
        if(!isPasswordValid) {
            throw new Error("密码错误");
        }

        const token = await this.jwt.signAsync({ username: user[0].username});
        return {
            access_token: token
        };
    }

    async signup (username: string, password: string) {
        const user = await this.userRepository.find(username);
        if (user) throw new Error("用户已存在"); 
        return this.userRepository.create({ username, password });
    }
}